<?php

namespace app\common\model;

use think\Exception;
use think\Model;


class Relation extends Model
{





    // 表名
    protected $name = 'user_relation';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];



	/**
	 * 添加团队记录
	 */
	public static function addRelation($uid,$relation)
	{
		$relation = explode("-",$relation);
		$level = 1;
		$key1 = 1;
		foreach ($relation as $k=>$v){
			if ($v === ''){
				continue;
			}
			$arr[$key1]['uid'] = $uid;
			$arr[$key1]['pid'] = $v;
			$arr[$key1]['level'] = $level;
			$arr[$key1]['created_at'] = time();
			$arr[$key1]['updated_at'] = time();
			$level++;
			$key1++;
		}
		$model = new self();
		$model->insertAll($arr);
	}
	/**
	 * 更新团队记录
	 */
	public static function saveRelation($uid,$relation)
	{
		$model = new self();
		$list = $model->where('uid', $uid)->select();
		foreach ($list as $k=>$v){
			$v->delete();
		}
		$relation = explode("-",$relation);
		$level = 1;
		$key1 = 1;
		foreach ($relation as $k=>$v){
			if ($v === ''){
				continue;
			}
			$arr[$key1]['uid'] = $uid;
			$arr[$key1]['pid'] = $v;
			$arr[$key1]['level'] = $level;
			$arr[$key1]['created_at'] = time();
			$arr[$key1]['updated_at'] = time();
			$level++;
			$key1++;
		}
		$model = new self();
		$model->insertAll($arr);
	}

    /**
     * 修改用户关系
     */
    public static function updateUserRelation($user,$invite_code)
    {
        $upUser = \app\admin\model\User::where('invite_code',$invite_code)->find();
        if(empty($upUser)){
            throw new Exception("会员信获取失败");
        }
        if($user['id'] == $upUser['id']){
            throw new Exception("不能绑定自己为上级");
        }
        if($user['referee'] == $upUser['id']){
            throw new Exception("上级关系已绑定，无需修改");
        }
        if(in_array($user['id'],explode("-",$upUser['relation']))){
            throw new Exception("上级团队包含自己，不能把下级设为自己的上级,无法修改");
        }
        $relation = trim($upUser['id']."-".$upUser['relation']);
        $user->save(['referee'=>$upUser['id'],'relation'=>$relation]);
        \app\common\model\Relation::saveRelation($user['id'],$relation);
        $list = \app\common\model\Relation::where('pid',$user['id'])->field('uid,pid,level')->select();
        if(!empty($list)){
            $rule = "/(\b".$user['id']."\b\-)(.*)/";
            foreach ($list as $ks=>$vs){
                $pidUser = \app\admin\model\User::where('id',$vs['uid'])->find();
                if(empty($pidUser)){
                    throw new Exception("会员信获取失败2");
                }
                $rela = trim(preg_replace($rule, '${1}'.$relation, $pidUser["relation"]),'-');
                $pidUser->save(['relation'=>$rela]);
                \app\common\model\Relation::saveRelation($vs['uid'],$rela);
            }
        }
    }


}
